﻿#include "MainWindow.h"

#include <QDebug>
#include <QGraphicsView>
#include <QHBoxLayout>
#include <QStackedWidget>
#include <QStatusBar>
#include <QVBoxLayout>

#include "ElaContentDialog.h"
#include "ElaDockWidget.h"
#include "ElaEventBus.h"
#include "ElaLog.h"
#include "ElaMenu.h"
#include "ElaMenuBar.h"
#include "ElaProgressBar.h"
#include "ElaStatusBar.h"
#include "ElaText.h"
#include "ElaTheme.h"
#include "ElaToolBar.h"
#include "ElaToolButton.h"
#include "ElaMessageBar.h"
#include "vtkXMLUnstructuredGridReader.h"
#include "vtkErrorCode.h"
//#include "T_Navigation.h"
#include "CenterWidget.h"
#include <QFileInfo>
#include <QStandardItem>
#include <vtkDelimitedTextReader.h>
#include <vtkDataSetMapper.h>
#include <vtkScalarBarActor.h>
#include <vtkActor.h>
#include <vtkTable.h>
#include <vtkLookupTable.h>
#include <vtkDataSet.h>
#include <vtkPointData.h>
#include <QVector>
#include <QList>
#include <QPair>
#include "QTextReader.h"
#include "TextFileParser.h"
#include "SelectDatatDialog.h"
#include "parser/jsonParser.h"
#include "ElaPushButton.h"
#include <ElaTreeView.h>
#include "Graph2D.h"
#include "Graph3D.h"
#include "Graph2DSettings.h"
#include "ElaWindow.h"
#include "BaseModule/IBaseSignal.h"
#include "BaseModule/GlobalHelper.h"
#include <set>
#include "Curve2DPlotor.h"
#include "NearFieldDataGenerator.h"


namespace pst
{

    MainWindow::MainWindow(QWidget* parent)
        : ElaWindow(parent)
        , m_textReader(nullptr)
        , m_textFileParser(new TextFileParser(this))
        , m_centerWidget(new CenterWidget(this))
        , m_selecetDataDialog(nullptr)
        , m_nearFieldDataGenerator(new NearFieldDataGenerator(this))
        , m_delimitedTextReader(vtkSmartPointer< vtkDelimitedTextReader>::New())
    {
        initWindow();
        initToolBar();
        initStatusBar();
        //中心窗口
        initContentWidget();

        connect(IBaseSignalInstance, &BaseModule::IBaseSignal::signal_readyCloseApp, this, [=](bool& isClose) {
            //isClose = false;//false表示不允许关闭
            //IBaseSignalInstance->signal_sendErrorMessageToUI(QStringLiteral("程序正在运行中，暂时不能关闭，请稍候。"));
            });

        //移动到中心
        moveToCenter();
        GlobalHelperInstance->sendMsgToParentProcess(QString("{--}winId{||}%1{--}\n").arg(winId()));

        initConnections();
    }

    MainWindow::~MainWindow()
    {
        for (auto i : m_vtuReader)
        {
            if (i != nullptr) i->Delete();
        }
    }

    //北航集成hirf的读文件
    void MainWindow::importHirf2DData()
    {
        auto t1 = clock();
        QString filePath = m_inputDir + "/data.txt";
        QString formartedPath = m_inputDir + "/dataFormated.txt";

        changeHirf2DDataFormat(filePath, formartedPath);
        //QString filePath = R"(D:\data\集成测试数据\hirf\point8.txt)";
        //auto filePath = R"(D:\data\同济\data.txt)";
        //std::cout << " filePath = " << filePath.toStdString() << std::endl;
        if (m_textReader != nullptr)
        {
            delete m_textReader; m_textReader = nullptr;
        }
        m_textReader = new QTextReader(this);
        m_textReader->setFilePath(formartedPath);
        m_textReader->setHasHeader(true);
        m_textReader->setSplitter(" ");
        QString errorMsg{};
        auto isOk = m_textReader->doRead(errorMsg);
        auto t2 = clock();

        //m_textFileParser = new TextFileParser(this);
        //m_textFileParser->SetFileName(filePath);
        //m_textFileParser->Update();
        auto t3 = clock();

        if (!isOk)
        {
            ElaMessageBar::error(ElaMessageBarType::PositionPolicy::BottomLeft, "错误", errorMsg, 1000, this);
            return;
        }
        else
        {
            ElaMessageBar::success(ElaMessageBarType::PositionPolicy::BottomLeft, "数据读取成功", "", 1000, this);

        }

        auto data = m_textReader->getAllData();
        if (data.size() < 2)
        {
            ElaMessageBar::error(ElaMessageBarType::PositionPolicy::BottomLeft, "错误", "数据列数不足", 1000, this);
            return;
        }
        auto x = data[0];

        //Hirf 前n-1个在一个窗口
        auto graph1 = m_centerWidget->addNewGraph2D();
        for (int i = 1; i < data.size() - 1; i++)
        {
            auto& y = data[i];
            m_centerWidget->addLineToGrapg2D(graph1, x, y);
        }

        //Hirf 最后一个单独开个窗口
        auto& yLast = data[data.size() - 1];
        auto graph2 = m_centerWidget->addNewGraph2D();
        m_centerWidget->setCurrentGraphWindow(graph2);
        m_centerWidget->addLineToGrapg2D(graph2, x, yLast);
        graph2->getPlotor()->setYAxisTitleName("屏蔽效能(dB)");
        graph2->getSettings()->setYAxisName("屏蔽效能(dB)");
    }

    void MainWindow::changeHirf2DDataFormat(const QString& inputFilePath, const QString& outputFilePath)
    {
        QFile file(inputFilePath);
        // 打开输入文件  
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug() << "无法打开文件:" << inputFilePath;
            return;
        }

        // 读取文件内容  
        QTextStream in(&file);
        QVector<QStringList> data;

        // 逐行读取  
        while (!in.atEnd()) {
            QString line = in.readLine().trimmed();
            if (!line.isEmpty()) {
                QStringList row = line.split(QRegularExpression("\\s+"), QString::SkipEmptyParts);
                data.append(row);
            }
        }
        file.close();

        // 处理数据，计算第五列  
        QVector<QStringList> outputData;
        QStringList header = { "Frequence(GHz)", "Ex(V/m)", "Ey(V/m)", "Ez(V/m)","BadWeatherCondition","ApprovalEnvironment", "shieldingEfficiency" };
        outputData.append(header);

        for (const QStringList& row : data) {
            if (row.size() >= 4) {
                double ex = row[1].toDouble();
                double ey = row[2].toDouble();
                double ez = row[3].toDouble();

                // 计算平方和，再开根号  
                auto ETotal = std::sqrt(ex * ex + ey * ey + ez * ez);
                double shieldingEfficiency = -20 * std::log10(ETotal);
                double BadWeatherCondition = 90 * ETotal;
                double ApprovalEnvironment = 100 * ETotal;
                QStringList outputRow = row;
                outputRow.append(QString::number(BadWeatherCondition, 'f', 6)); // 保留6位小数  
                outputRow.append(QString::number(ApprovalEnvironment, 'f', 6)); // 保留6位小数  
                outputRow.append(QString::number(shieldingEfficiency, 'f', 6)); // 保留6位小数  
                outputData.append(outputRow);
            }
        }

        // 写入输出文件  
        QFile outFile(outputFilePath);
        if (!outFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qDebug() << "无法打开文件:" << outputFilePath;
            return;
        }

        QTextStream out(&outFile);
        // 写入数据到文件  
        for (const QStringList& row : outputData) {
            out << row.join(" ") << "\n";
        }
        outFile.close();

        qDebug() << "Hirf2D数据格式处理完成，结果已写入:" << outputFilePath;
    }

    void MainWindow::importJingDian3DAs2D()
    {
        auto fileName = m_inputDir + "/data.txt";
        //auto fileName = R"(D:\data\集成测试数据\静电\data.txt)";
        m_centerWidget->addImageToNewSurfaceWindow(fileName);
    }

    void MainWindow::slot_importProjectData(const QStringList& filepathList)
    {
        //m_simuType = "Hirf2D";
        if (m_simuType.isEmpty())
        {
            JsonParser* jsonParser = JsonParser::GetInstance();
            auto resultData = jsonParser->GetResultData(filepathList.toVector());
            const auto& projectData = resultData.projectData;
            if (!projectData.isNull()) {
                for (const auto& data : projectData->projectResultData) {
                    auto qFileInfo = QFileInfo(data->filePath);
                    QStandardItem* item = new QStandardItem(qFileInfo.fileName());
                    m_centerWidget->addFileNode(item);
                    m_fileType[item] = data;
                }
            }
            if (!resultData.errorMessageList.isEmpty()) {
                //auto errorMsg = resultData.errorMessageList.join("\n");
                //ElaMessageBar::error(ElaMessageBarType::PositionPolicy::BottomLeft, "错误", errorMsg, 1000, this);
                m_errorMessageList.append(std::move(resultData.errorMessageList));
                //auto errorMsg = resultData.errorMessageList.join("\n");
                //emit IWidgetSignalInstance->signal_sendErrorMessageToUI(errorMsg);
            }
        }
        else if (m_simuType == "Hirf2D")
        {
            std::cout << "data type = Hirf2D" << std::endl;
            importHirf2DData();
        }
        else if (m_simuType == "StaticElectricity")
        {
            std::cout << "StaticElectricity" << std::endl;
            importJingDianData();
        }
        else if (m_simuType == "StaticElectricity3DAs2D")
        {
            std::cout << "StaticElectricity3DAs2D" << std::endl;
            importJingDian3DAs2D();
        }
        else
        {
            std::cout << "unkown type!" << std::endl;
        }







        //QString filePath = R"(C:\Users\12\Desktop\jiezhiqiu RCS_2D_test.txt)";
        //if (!(rand() % 3)) {
        //    filePath = R"(C:\Users\12\Desktop\GainDirectionFile_2D.txt)";
        //}
        //std::cout << " filePath = " << filePath.toStdString() << std::endl;
        //m_textFileParser->SetFileName(filePath);
        //auto isOk = m_textFileParser->Update();

        //if (!isOk)
        //{
        //    auto errorMsg = m_textFileParser->getErrorMessage();
        //    ElaMessageBar::error(ElaMessageBarType::PositionPolicy::BottomLeft, "错误", errorMsg, 1000, this);
        //    return;
        //}

        //ElaToolButton* _btn = dynamic_cast<ElaToolButton*>(sender());
        //ElaMessageBar::success(ElaMessageBarType::PositionPolicy::BottomLeft, _btn->text(), "成功", 1000, this);


        //auto qFileInfo = QFileInfo(filePath);
        ////m_fileType[filePath] = "File2DCurve";
        //QStandardItem* item = new QStandardItem(qFileInfo.fileName());
        //FileInfo info;
        //info.m_filePath = filePath;
        //info.m_fileType = FileDataType::File2DCurve;
        //m_centerWidget->addFileNode(item);
        //m_fileType[item] = info;
    }

    void MainWindow::slot_read3DData(const QString& filePath)
    {
        if (filePath.isEmpty()) {
            return;
        }
        //QString filePath = filepath;

        vtkXMLUnstructuredGridReader* reader = vtkXMLUnstructuredGridReader::New();
        reader->SetFileName(filePath.toStdString().c_str());
        reader->Update();
        int errorCode = reader->GetErrorCode();
        if (errorCode != 0)
        {
            //int lastErrorCode = reader->GetErrorCode();
            //const char* lastErrorString = vtkErrorCode::GetStringFromErrorCode(lastErrorCode);
            //ElaMessageBar::error(ElaMessageBarType::PositionPolicy::BottomLeft, "错误", lastErrorString, 1000, this);
            m_errorMessageList.append(filePath);
            return;
        }


        //ElaToolButton* _btn = dynamic_cast<ElaToolButton*>(sender());
        //ElaMessageBar::success(ElaMessageBarType::PositionPolicy::BottomLeft, "读取三维数据", "成功", 1000, this);

        QFileInfo qFileInfo(filePath);
        QStandardItem* item = new QStandardItem(qFileInfo.fileName());
        //FileInfo info;
        //info.m_filePath = filePath;
        //info.m_fileType = FileDataType::File3DGraph;
        //m_centerWidget->addFileNode(item);

        //后续应该改为从JsonParser读取三维结果
        QSharedPointer<ResultDataInfo> info = QSharedPointer<ResultDataInfo>(new ResultDataInfo);
        info->filePath = filePath;
        info->fileType = FileDataType::File3DGraph;
        m_centerWidget->addFileNode(item);
        m_fileType[item] = info;
        m_vtuReader[item] = reader;
    }

    void MainWindow::slot_checkGraphType(const QList<QStandardItem*>& indexs)
    {
        QList<FileDataTypes> inputType;

        for (auto index : indexs)
        {
            auto it = m_fileType.find(index);
            if (it != m_fileType.end())
            {
                inputType.append(it.value()->fileType);
            }
        }
        bool is2D = false;
        bool isPolar = false;
        bool is3D = false;
        checkFileType(inputType, is2D, isPolar, is3D);

        if (indexs.size() > 1)// 不允许同时选择多个3D图
        {
            is3D = false;
        }
        m_toolButton3DGraph->setEnabled(is3D);
        m_toolButton2DGraph->setEnabled(is2D);
        m_toolButtonPolarGraph->setEnabled(isPolar);

        m_currentChosenFiles = indexs;
    }

    void MainWindow::slot_displayNew2DGraph()
    {
        m_selectFileList.clear();
        m_optionalKeyList.clear();
        for (const auto& item : m_currentChosenFiles) {
            auto it = m_fileType.find(item);
            if (it != m_fileType.end())
            {
                m_selectFileList.append(it.value());
            }
        }
        if (m_selectFileList.size() > 1) {
            QSet<QString> repeatKey;
            for (int i = 0; i < m_selectFileList.size(); ++i) {
                auto& textFileParser = m_selectFileList.at(i)->resultData;
                if (i == 0) {
                    repeatKey = textFileParser.getEachColNameOfKey().toList().toSet();
                }
                else {
                    repeatKey = repeatKey.intersect(textFileParser.getEachColNameOfKey().toList().toSet());
                }
            }
            m_optionalKeyList = repeatKey.toList();
            if (m_optionalKeyList.isEmpty()) {
                //ElaMessageBar::error(ElaMessageBarType::PositionPolicy::BottomLeft, "错误", "没有公共key", 1000, this);
                //ElaContentDialog* errorDialog = new ElaContentDialog(this);
                //errorDialog->setMiddleButtonVisible(false);
                //errorDialog->setTitleText(tr("提示"));
                //errorDialog->setContentText(tr("数据变量不一致，请重新选择工程文件"));
                //errorDialog->exec();
                emit IBaseSignalInstance->signal_sendErrorMessageToUI("数据变量不一致，请重新选择工程文件");
                return;
            }
        }
        ShowSelecetDataDialog();
        //for (auto index : m_currentChosenFiles)
        //{
        //    auto it = m_fileType.find(index);
        //    if (it != m_fileType.end())
        //    {
        //        m_centerWidget->display2DGraph(it.value().m_filePath);
        //    }
        //}
        ////顶级选择数据对话框

        //////次级选择数据对话框
        //DataChosenListDialog* m_dataChosenListDialog = new DataChosenListDialog(this);
        //m_dataChosenListDialog->setFixedSize(400, 400);
        //m_dataChosenListDialog->moveToCenter();
        //QList<QString> data{ "-180deg", "-90deg", "0deg", "90deg", "180deg" };
        //m_dataChosenListDialog->setData(data);
        //m_dataChosenListDialog->show();
        //m_dataChosenListDialog->updateUI();
        //QList<int> indexs{ 1, 2 };
        //m_dataChosenListDialog->setSelctedIndexs(indexs);


        //        //只取第首个文件
        //if (m_currentChosenFiles.isEmpty())
        //{
        //    return;
        //}
        //auto index = m_currentChosenFiles.at(0);
        //auto it = m_fileType.find(index);
        //if (it != m_fileType.end())
        //{
        //    auto data = m_textReader->getAllData();
        //    if (data.size() < 2)
        //    {
        //        ElaMessageBar::error(ElaMessageBarType::PositionPolicy::BottomLeft, "错误", "数据列数不足", 1000, this);
        //        return;
        //    }
        //    auto x = data[0];
        //    for (int i = 1; i < data.size(); i++)
        //    {
        //        auto& y = data[i];
        //        m_centerWidget->addLineToGrapg2D(x, y);
        //    }
        //    //展示数据
        //}

    }

    void MainWindow::slot_displayNew3DGraph()
    {
        auto selectedItems = m_centerWidget->getSelectedItems();

        QList<InfomationGraph3DBasical> infoList;
        for (auto index : selectedItems)
        {
            auto it = m_fileType.find(index);
            if (it != m_fileType.end())
            {
                InfomationGraph3DBasical info;
                info.m_reader = m_vtuReader[index];
                infoList.append(info);
            }
        }
        m_centerWidget->addImageToNewGraph3DWindow(infoList, m_openNewWindow);
        m_openNewWindow = true;
    }

    void MainWindow::slot_displayNewSurfaceGraph()
    {
        //QString fileName = R"(D:\data\RCSFile_threeColumes - plane.txt)";
        QString fileName = QFileDialog::getOpenFileName(
            this, tr("选择 TXT 文件"), "", tr("文本文件 (*.txt);;所有文件 (*)"));

        if (fileName.isEmpty())
        {
            return;
        }
        m_centerWidget->addImageToNewSurfaceWindow(fileName);
        m_openNewWindow = true;
    }

    void MainWindow::slot_saveGraphToLocal()
    {
        QString fileName = QFileDialog::getSaveFileName(this, tr("保存截图"), m_outputDir, // 默认文件名  
            tr("PNG 文件 (*.png);;JPG 文件 (*.jpg)")); // 文件过滤器 

        if (fileName.isEmpty())
        {
            return;
        }

        //auto fileName = m_outputDir + "/ScreenShot" + QString::number(m_screenShotNum++) + ".jpg";
        auto isSuc = m_centerWidget->saveScreenShot(fileName);
        //std::cout << "isSuc = " << isSuc << std::endl;
        //isSuc ? ElaMessageBar::success(ElaMessageBarType::PositionPolicy::BottomLeft, m_toolButtonSaveImageToLocal->text(), "成功: " + fileName, 1000, this)
        //    : ElaMessageBar::error(ElaMessageBarType::PositionPolicy::BottomLeft, m_toolButtonSaveImageToLocal->text(), "失败: " + fileName, 1000, this);
        if (!isSuc)
        {
            emit IBaseSignalInstance->signal_sendErrorMessageToUI("失败: " + fileName);
        }
    }

    void MainWindow::slot_sendSelectedInfo(int& variableIndex,
        QList<QPair<int, QList<int>>>& chosenData, QList<int>& valueIndexs)
    {
        if (m_selectFileList.isEmpty()) {
            return;
        }
        auto* textFileparser = &m_selectFileList.takeFirst()->resultData;

        QVector<QVector<double>> keyList = textFileparser->getEachColDataOfKey();
        QVector<QVector<double>> otherKeyData;
        for (const auto& i : chosenData)
        {
            QVector<double> singleColmValue;
            for (auto j : i.second)
            {
                singleColmValue.append(keyList[i.first][j]);

            }
            otherKeyData.append(singleColmValue);
        }
        qDebug() << "variableIndex = " << variableIndex
            << " \n chosenData = " << chosenData
            << " \n valueIndexs = " << valueIndexs;
        textFileparser->setScanParameterIndex(variableIndex);
        textFileparser->setOtherKeyParameter(otherKeyData);


        QList<InfomationCurve2DBasical> infoList;
        textFileparser->getChosenLinesFromKey(valueIndexs, infoList);
        static QList<InfomationCurve2DBasical> s_infoList;
        s_infoList.append(std::move(infoList));

        //Graph2D* newGraph = m_centerWidget->addNewGraph2D();
        //m_centerWidget->setCurrentTab(newGraph);
        //QPair<QString, QVector<double>> tempx;


        //for (InfomationCurve2DBasical& i : infoList)
        //{
        //    i.setGraph(newGraph);
        //    m_centerWidget->addLineToGrapg2D(i);
        //}
        if (m_selectFileList.isEmpty()) {
            m_centerWidget->addLinesToNewGrapg2DWindow(s_infoList, m_openNewWindow);
            m_openNewWindow = true;
            s_infoList.clear();
            m_optionalKeyList.clear();
        }
        else {
            if (m_optionalKeyList.size() > 1) {
                m_optionalKeyList = { textFileparser->getEachColNameOfKey().at(variableIndex) };
            }
            ShowSelecetDataDialog();
        }
    }

    void MainWindow::slot_sendQuestionMessageToUI(int& result, const QString& title, const QString& message)
    {
        auto _closeDialog = new ElaContentDialog(this);
        _closeDialog->setTitleText(title);
        _closeDialog->setContentText(message);
        _closeDialog->setUseMultilineText(true);

        connect(_closeDialog, &ElaContentDialog::leftButtonClicked, [=]() { _closeDialog->reject(); }); //取消
        connect(_closeDialog, &ElaContentDialog::rightButtonClicked, [=]() { _closeDialog->accept(); });    //确定

        result = _closeDialog->exec();
    }

    void MainWindow::slot_sendErrorMessageToUI(const QString& message)
    {
        auto _closeDialog = new ElaContentDialog(this);
        _closeDialog->setTitleText("错误");
        _closeDialog->setContentText(message);
        _closeDialog->setUseMultilineText(true);
        _closeDialog->setLeftButtonVisible(false);

        connect(_closeDialog, &ElaContentDialog::leftButtonClicked, [=]() { _closeDialog->reject(); }); //取消
        connect(_closeDialog, &ElaContentDialog::rightButtonClicked, [=]() { _closeDialog->accept(); });    //确定

        _closeDialog->exec();
    }

    void MainWindow::slot_addToCurrentGraph(const QList<QStandardItem*>& index)
    {
        auto currentGraph = m_centerWidget->getCurrentGraphWindow();
        //借助slot_checkGraphType判断的按钮是否可用来判断选中数据类型
        if (qobject_cast<Graph2D*>(currentGraph) != nullptr && m_toolButton2DGraph->isEnabled())
        {
            m_openNewWindow = false;
            slot_displayNew2DGraph();
        }
        else if (qobject_cast<Graph3D*>(currentGraph) != nullptr && m_toolButton3DGraph->isEnabled())
        {
            m_openNewWindow = false;
            slot_displayNew3DGraph();
        }
        else
        {
            IBaseSignalInstance->signal_sendErrorMessageToUI("数据类型不一致");
            return;
        }

    }

    void MainWindow::initWindow()
    {
        setIsNavigationBarEnable(false);
        setWindowButtonFlags((ElaAppBarType::ButtonFlags)ElaAppBarType::StayTopButtonHint | ElaAppBarType::MinimizeButtonHint | ElaAppBarType::MaximizeButtonHint | ElaAppBarType::CloseButtonHint);
        setAppBarHeight(32);
        setWindowIcon(QIcon("://QUI/icon/nodeset.png"));
        resize(1678, 921);
        setWindowTitle("统一后处理平台");
        this->setWindowButtonFlag(ElaAppBarType::StayTopButtonHint, false);
        this->setStyleSheet("QWidget{background-color: #FFFFFF}");
    }

    void MainWindow::initStatusBar()
    {
        //状态栏
        ElaStatusBar* statusBar = new ElaStatusBar(this);
        ElaText* statusText = new ElaText("初始化成功！", this);
        statusText->setTextPixelSize(14);
        statusBar->addWidget(statusText);
        this->setStatusBar(statusBar);
    }

    void MainWindow::slot_toolBtnClick()
    {
        ElaWidget* widget = new ElaWidget();
        widget->setWindowTitle(tr("数据导入"));
        widget->setWindowButtonFlag(ElaAppBarType::StayTopButtonHint, false);
        widget->setWindowModality(Qt::ApplicationModal);
        QHBoxLayout* hBoxLayout = new QHBoxLayout(this);
        ElaPushButton* localImport = new ElaPushButton(tr("本地导入"), widget);
        hBoxLayout->addWidget(localImport);
        ElaPushButton* databaseImport = new ElaPushButton(tr("数据库导入"), widget);
        databaseImport->setEnabled(false);
        hBoxLayout->addWidget(databaseImport);
        hBoxLayout->setSpacing(20);
        hBoxLayout->setMargin(50);
        hBoxLayout->setSizeConstraint(QLayout::SetFixedSize);
        widget->setLayout(hBoxLayout);
        widget->show();
        connect(localImport, &ElaPushButton::clicked, [this, widget]() {
            auto filepathList = QFileDialog::getOpenFileNames(nullptr, QString(), m_inputDir, tr("数据文件(*.txt *.vtu)"));
            QFileInfo fileInfo;
            QStringList textList;
            m_errorMessageList.clear();
            for (const auto& filepath : filepathList) {
                fileInfo.setFile(filepath);
                if (fileInfo.completeSuffix() == "txt") {
                    textList.append(fileInfo.absoluteFilePath());
                }
                else if (fileInfo.completeSuffix() == "vtu") {
                    slot_read3DData(fileInfo.absoluteFilePath());
                }
            }
            slot_importProjectData(textList);
            if (!m_errorMessageList.isEmpty()) {
                ElaContentDialog* errorDialog = new ElaContentDialog(this);
                errorDialog->setUseMultilineText(true);
                errorDialog->setMiddleButtonVisible(false);
                errorDialog->setTitleText(tr("导入失败列表"));
                errorDialog->setContentText(m_errorMessageList.join("\n"));
                errorDialog->exec();
            }
            m_errorMessageList.clear();
            widget->deleteLater();
            });


        //ElaToolButton* _btn = dynamic_cast<ElaToolButton*>(sender());
        //if (_btn)
        //{
        //    ElaMessageBar::success(ElaMessageBarType::PositionPolicy::BottomLeft, _btn->text(), "成功", 1000, this);
        //}
    }

    void MainWindow::importJingDianData()
    {
        auto fileName = m_inputDir + "/data.txt";
        bool isSuc = this->readerDelimitedTextFromLocal(fileName);
        if (!isSuc)
        {
            std::cout << "Read data fail!";
            return;
        }
        m_nearFieldDataGenerator->setInputData(m_delimitedTextReader->GetOutput());
        m_nearFieldDataGenerator->inverserXYZ(true);
        m_nearFieldDataGenerator->update();
        auto m_dataSet = m_nearFieldDataGenerator->getOutputData(); //structuredGrid
        double* range = m_dataSet->GetPointData()->GetArray(0)->GetRange();

        vtkNew<vtkLookupTable> m_lookupTable;
        m_lookupTable->SetNumberOfColors(150);
        m_lookupTable->SetHueRange(0.67, 0.0);
        m_lookupTable->Build();
        m_lookupTable->SetRange(range);

        vtkNew<vtkDataSetMapper> m_dataMapper;
        m_dataMapper->SetInputData(m_dataSet);
        m_dataMapper->SetLookupTable(m_lookupTable);
        m_dataMapper->SetInterpolateScalarsBeforeMapping(true);
        m_dataMapper->SetUseLookupTableScalarRange(1);
        m_dataMapper->ScalarVisibilityOn();

        vtkNew<vtkActor> m_dataActor;
        m_dataActor->SetMapper(m_dataMapper);

        vtkNew<vtkScalarBarActor> m_scalarBarActor;
        m_scalarBarActor->SetBarRatio(0.25);
        //m_scalarBarActor->GetTitleTextProperty()->SetJustificationToLeft();
        m_scalarBarActor->SetPosition(0.9, 0.1);
        m_scalarBarActor->SetPosition2(0.05, 0.7);
        m_scalarBarActor->SetNumberOfLabels(10);
        m_scalarBarActor->SetLookupTable(m_lookupTable);

        auto graph = m_centerWidget->addNewGraph3D();
        QList<vtkProp*> props;
        props << m_dataActor << m_scalarBarActor;
        graph->addProp(props);
    }

    void MainWindow::slot_exportBtnClick()
    {
        auto graph = qobject_cast<Graph2D*>(m_centerWidget->getCurrentGraphWindow());
        auto plotor = graph->getPlotor();
        auto& curveMap = graph->getCurve();
        QList<double> keyData;
        for (const auto& curve : curveMap) {
            keyData.append(curve.getXData().second.toList());
        }
        qDebug() << "keyData befor " << keyData;
        std::set s(keyData.begin(), keyData.end());
        keyData = QList<double>::fromStdList(std::list(s.begin(), s.end()));
        auto count = plotor->graphCount();
        for (int i = 0; i < count; ++i) {
            qDebug() << "keyData after " << keyData;
            for (auto d : keyData) {
                qDebug() << "d " << d << "i " << i;
                qDebug() << plotor->graph(i)->data().data()->findBegin(d, false)->key << plotor->graph(i)->data().data()->findBegin(d)->value << plotor->graph(i)->data().data()->findBegin(d)->mainKey() << plotor->graph(i)->data().data()->findBegin(d)->mainValue();
            }
        }
    }

    void MainWindow::initToolBar()
    {
        //工具栏
        ElaToolBar* toolBar = new ElaToolBar("工具栏", this);
        toolBar->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea);
        toolBar->setAllowedAreas(Qt::NoToolBarArea);
        toolBar->setToolBarSpacing(5);
        toolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
        toolBar->setIconSize(QSize(25, 25));
        toolBar->setFloatable(false);
        toolBar->setMovable(false);
        toolBar->setContentsMargins(QMargins(5, 5, 5, 5));
        toolBar->setStyleSheet("QToolBar {\
            background - color: #C9CDD0;\
        border - bottom: 1px solid #FAFAFA;\
    padding: 1px;\
        font - weight: bold;\
    spacing: 2px;\
    }");

        ElaToolButton* toolButton1 = new ElaToolButton(this);
        //toolButton1->setElaIcon(ElaIconType::FileImport);
        toolButton1->setIcon(QIcon(":/QUI/image/data_import.png"));
        toolButton1->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        toolButton1->setText("数据导入");
        toolButton1->setEnabled(false);
        toolBar->addWidget(toolButton1);
        connect(toolButton1, &ElaToolButton::clicked, this, &MainWindow::slot_toolBtnClick);

        ElaToolButton* toolButton2 = new ElaToolButton(this);
        //toolButton2->setElaIcon(ElaIconType::FileExport);
        toolButton2->setIcon(QIcon(":/QUI/image/data_export.png"));
        toolButton2->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        toolButton2->setText("数据导出");
        toolButton2->setEnabled(false);
        toolBar->addWidget(toolButton2);
        connect(toolButton2, &ElaToolButton::clicked, this, &MainWindow::slot_exportBtnClick);

        ElaToolButton* toolButton3 = new ElaToolButton(this);
        //toolButton3->setElaIcon(ElaIconType::ArrowDownToBracket);
        toolButton3->setIcon(QIcon(":/QUI/image/result_import.png"));
        toolButton3->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        toolButton3->setText("工程结果导入");
        //toolButton3->setEnabled(false);
        toolBar->addWidget(toolButton3);
        connect(toolButton3, &ElaToolButton::clicked, [this]() {
            QDir dir(m_inputDir);
            QDir::setCurrent(m_inputDir);
            const auto& fileList = dir.entryList(QDir::Files);
            slot_importProjectData(fileList); 
            });

        //connect(toolButton3, &ElaToolButton::clicked, this, &MainWindow::importJingDianData);

        ElaToolButton* toolButton4 = new ElaToolButton(this);
        //toolButton4->setElaIcon(ElaIconType::SquareStar);
        toolButton4->setIcon(QIcon(":/QUI/image/standard_format_view.png"));
        toolButton4->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        toolButton4->setText("标准格式查看");
        toolBar->addWidget(toolButton4);
        toolButton4->setEnabled(false);
        toolBar->addSeparator();

        m_toolButton3DGraph = new ElaToolButton(this);
        //m_toolButton3DGraph->setElaIcon(ElaIconType::CloudMeatball);
        m_toolButton3DGraph->setIcon(QIcon(":/QUI/image/3d_graph.png"));
        m_toolButton3DGraph->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        m_toolButton3DGraph->setText("三维图");
        m_toolButton3DGraph->setEnabled(false);
        toolBar->addWidget(m_toolButton3DGraph);

        m_toolButton2DGraph = new ElaToolButton(this);
        //m_toolButton2DGraph->setElaIcon(ElaIconType::BezierCurve);
        m_toolButton2DGraph->setIcon(QIcon(":/QUI/image/2d_graph.png"));
        m_toolButton2DGraph->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        m_toolButton2DGraph->setText("二维图");
        m_toolButton2DGraph->setEnabled(false);
        toolBar->addWidget(m_toolButton2DGraph);

        m_toolButtonPolarGraph = new ElaToolButton(this);
        //m_toolButtonPolarGraph->setElaIcon(ElaIconType::CircleWaveformLines);
        m_toolButtonPolarGraph->setIcon(QIcon(":/QUI/image/polar_graph.png"));
        m_toolButtonPolarGraph->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        m_toolButtonPolarGraph->setText("极坐标图");
        m_toolButtonPolarGraph->setEnabled(false);
        toolBar->addWidget(m_toolButtonPolarGraph);
        toolBar->addSeparator();

#ifdef _DEBUG
        //m_toolButtonSurfaceGraph = new ElaToolButton(this);
        ////m_toolButtonSurfaceGraph->setElaIcon(ElaIconType::Rectangle);
        //m_toolButtonSurfaceGraph->setIcon(QIcon(":/QUI/image/3d_graph.png"));
        //m_toolButtonSurfaceGraph->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        //m_toolButtonSurfaceGraph->setText("三维平面图");
        ////m_toolButtonSurfaceGraph->setEnabled(false);
        //m_toolButtonSurfaceGraph->setVisible(false);
        //toolBar->addWidget(m_toolButtonSurfaceGraph);
        //toolBar->addSeparator();
#endif
        //ElaToolButton* toolButton8 = new ElaToolButton(this);
        //toolButton8->setElaIcon(ElaIconType::PresentationScreen);
        ////toolButton8->setIcon(QIcon(":/QUI/image/data_import.png"));
        //toolButton8->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        //toolButton8->setText("截图");
        //toolButton8->setEnabled(false);
        //toolBar->addWidget(toolButton8);

        ElaToolButton* toolButton9 = new ElaToolButton(this);
        //toolButton9->setElaIcon(ElaIconType::SquarePollHorizontal);
        toolButton9->setIcon(QIcon(":/QUI/image/screenshot_to_report.png"));
        toolButton9->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        toolButton9->setText("截图至报告");
        toolButton9->setEnabled(false);
        toolBar->addWidget(toolButton9);

        m_toolButtonSaveImageToLocal = new ElaToolButton(this);
        //m_toolButtonSaveImageToLocal->setElaIcon(ElaIconType::Image);
        m_toolButtonSaveImageToLocal->setIcon(QIcon(":/QUI/image/image_save.png"));
        m_toolButtonSaveImageToLocal->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        m_toolButtonSaveImageToLocal->setText("图片保存");
        toolBar->addWidget(m_toolButtonSaveImageToLocal);
        toolBar->setFixedHeight(72);

        this->addToolBar(Qt::TopToolBarArea, toolBar);


        connect(m_toolButton2DGraph, &ElaToolButton::clicked, [this]() {
            m_openNewWindow = true; slot_displayNew2DGraph(); });
        connect(m_toolButtonSaveImageToLocal, &ElaToolButton::clicked, this, &MainWindow::slot_saveGraphToLocal);
#ifndef NDEBUG
        connect(toolButton4, &ElaToolButton::clicked, [this]() {
            slot_read3DData(); });
#endif // NDEBUG
        connect(m_toolButton3DGraph, &ElaToolButton::clicked, this, &MainWindow::slot_displayNew3DGraph);
        connect(m_toolButtonSurfaceGraph, &ElaToolButton::clicked, this, &MainWindow::slot_displayNewSurfaceGraph);
    }

    void MainWindow::initContentWidget()
    {
        addPageNode("CenterWidget", m_centerWidget, ElaIconType::LocationArrow);
        connect(m_centerWidget, &CenterWidget::signal_fileClicked,
            this, &MainWindow::slot_checkGraphType);
        m_centerWidget->GetTreeView()->setSelectionMode(QAbstractItemView::ExtendedSelection);
    }

    void MainWindow::checkFileType(
        const QList<FileDataTypes>& inputType,
        bool& is2D, bool& isPolar, bool& is3D)
    {
        if (inputType.isEmpty())
        {
            return;
        }
        bool _is2D = true;
        bool _isPolar = true;
        bool _is3D = true;
        FileDataTypes fileDataType = 0xff;
        for (const auto& type : inputType)
        {
            fileDataType &= type;
        }
        _is2D = _is2D && (fileDataType & FileDataType::File2DCurve);
        _isPolar = _isPolar && (fileDataType & FileDataType::FilePolar);
        _is3D = _is3D && (fileDataType & FileDataType::File3DGraph);
        is2D = _is2D;
        isPolar = _isPolar;
        is3D = _is3D;
    }

    void MainWindow::ShowSelecetDataDialog()
    {
        //保证每次都是一个新的选择框
        if (m_selecetDataDialog != nullptr)
        {
            m_selecetDataDialog->deleteLater(); m_selecetDataDialog = nullptr;
        }

        if (m_selectFileList.isEmpty()) {
            return;
        }

        m_selecetDataDialog = new SelectDatatDialog(this);

        auto* textFileParser = &m_selectFileList.first()->resultData;
        auto& keyNameList = textFileParser->getEachColNameOfKey();
        auto keyDataList = textFileParser->getEachColDataOfKey();
        QList<QPair<QString, QVector<double>>> keyData;
        for (int i = 0; i < keyNameList.size(); ++i)
        {
            keyData.append(QPair<QString, QVector<double>>(keyNameList[i], keyDataList[i]));
        }


        auto valueNameList = textFileParser->getEachColNameOfValue();
        auto valueDataList = textFileParser->getEachColDataOfValue();
        QList<QPair<QString, QVector<double>>> valueData;
        for (int i = 0; i < valueNameList.size(); ++i)
        {
            valueData.append(QPair<QString, QVector<double>>(valueNameList[i], valueDataList[i]));
        }
        m_selecetDataDialog->setFixedSize(400, 400);
        m_selecetDataDialog->moveToCenter();
        m_selecetDataDialog->setWindowModality(Qt::ApplicationModal);
        m_selecetDataDialog->SetOptionalKey(m_optionalKeyList);
        m_selecetDataDialog->show();
        //m_selecetDataDialog->setDialogTitle("方向性");
        m_selecetDataDialog->setKeyDataList(keyData);
        m_selecetDataDialog->setValueDataList(valueData);//其实不用传value的值，只需要名字
        m_selecetDataDialog->updateUI();


        connect(m_selecetDataDialog, &SelectDatatDialog::signal_sendSelectedInfo,
            this, &MainWindow::slot_sendSelectedInfo);
    }

    void MainWindow::initConnections()
    {
        connect(m_centerWidget, &CenterWidget::signal_addToCurrentGraph,
            this, &MainWindow::slot_addToCurrentGraph);
    }

    bool MainWindow::readerDelimitedTextFromLocal(const QString& fileName)
    {
        if (!vtksys::SystemTools::FileExists(fileName.toStdString(), true))
        {
            return false;
        }
        m_delimitedTextReader->SetFileName(fileName.toStdString().c_str());
        m_delimitedTextReader->SetHaveHeaders(true);
        m_delimitedTextReader->SetDetectNumericColumns(true);
        m_delimitedTextReader->SetFieldDelimiterCharacters(",");
        m_delimitedTextReader->SetUseStringDelimiter(true);
        m_delimitedTextReader->Update();
        if (m_delimitedTextReader->GetOutput() == nullptr)
        {
            return false;
        }
        return true;
    }
}
